<template>
  <el-drawer
    title="监控详情"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="clearDrawer"
    custom-class="tag-drawer monitor-detail-page"
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <div class="indicator-name">{{ tagNm }}</div>
        <org-list ref="orgList" :tagId="tagId" @changeOrg="changeOrg"></org-list>
        <code-list ref="codeList" :tagId="tagId" :orgId="orgId" @changeCode="handleCodeChange"></code-list>
        <div class="tag-data-wrap">
          <tag-content-header>
            <template #title>
              <span class="title-text">
                近7天历史数据
                <span class="title-tips">(点击相应柱状图或横坐标可设置代码值状态)</span>
              </span>
            </template>
          </tag-content-header>
          <template v-if="chartList.length">
            <div id="echart"></div>
          </template>
          <div class="no-record" v-else>暂无数据</div>
        </div>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="clearDrawer">关闭</el-button>
    </div>
  </el-drawer>
</template>

<script>
import orgList from './org-list'
import codeList from './code-list'
import $monitor from './api'
import * as echarts from 'echarts'
export default {
  name: 'TagDetail',
  components: {
    orgList,
    codeList
  },
  data() {
    return {
      drawerVisible: false,
      tagId: '',
      tagNm: '',
      orgId: '',
      chartList: [],
      dataChart: null
    }
  },
  methods: {
    showDrawer(params) {
      this.tagId = params.tagId
      this.tagNm = params.tagNm
      this.drawerVisible = true
      this.$nextTick(() => this.$refs.orgList.getList())
    },
    changeOrg(orgId) {
      this.orgId = orgId
      this.$nextTick(() => this.$refs.codeList.getResults())
    },
    handleCodeChange(data) {
      const { codeCd, codeDesc } = data
      this.getChartData({
        codeCd,
        codeDesc,
        orgId: this.orgId,
        tagId: this.tagId
      })
    },
    updateCodeStatus(data) {
      // 更新代码值状态
      let { orgId, tagId, codeCd, codeDesc, snapshotDate, alarmStatus } = data
      let obj = {
        orgId,
        tagId,
        codeCd,
        snapshotDate,
        alarmStatus
      }
      $monitor.updateCodeStatus(obj).then(({ data }) => {
        if (data && data.code === '0') {
          this.getChartData({
            codeCd,
            codeDesc,
            orgId: orgId,

            tagId
          })
          this.$message.success('更新成功')
        } else {
          this.message.error(data.data || data.msg)
        }
      })
    },
    getChartData(obj) {
      $monitor.historyData(obj).then(({ data }) => {
        if (data && data.code === '0') {
          this.chartList = data.data
          this.$nextTick(() => this.setChart(data.data))
        } else {
          this.message.error(data.data || data.msg)
        }
      })
    },
    setChartEvent() {
      this.dataChart.on('click', params => {
        let target = this.chartList.find(item => item.snapshotDate.substring(5) === params.value)
        let { alarmStatus, orgId, tagId, codeCd, codeDesc, snapshotDate } =
          params.componentType === 'xAxis' ? target : params.data

        this.$confirm(`是否将此数据标志为【${alarmStatus === 1 ? '正常' : '异常'}】状态`, '提示', {
          type: 'warning'
        }).then(() => {
          let messageBox = document.getElementsByClassName('el-message-box__wrapper')
          messageBox[0].focus() // 防止按空格键重复确定
          this.updateCodeStatus({
            orgId,
            tagId,
            codeCd,
            codeDesc,
            snapshotDate,
            alarmStatus: alarmStatus === 1 ? 0 : 1
          })
        })
      })
    },
    setChart(data) {
      if (!this.dataChart) {
        this.dataChart = echarts.init(document.getElementById('echart'))
        window.addEventListener('resize', () => {
          this.dataChart.resize()
        })
        this.setChartEvent()
      }
      let xAxis = []
      let fullDate = []
      let odata = []
      xAxis = data.map(item => item.snapshotDate)
      odata = data.map(v => {
        return {
          ...v,
          value: v.codeCount,
          itemStyle: {
            color: v.alarmStatus === 1 ? '#e6a23c' : '#4fa8f9'
          }
        }
      })
      for (let i = 0; i < 7; i++) {
        fullDate.push(this.getDay(-7 + i))
      }
      fullDate.forEach((date, index) => {
        if (!xAxis.includes(date)) {
          xAxis.splice(index, 0, date)
          odata.splice(index, 0, { value: '' })
        }
      })
      xAxis = xAxis.map(item => {
        return item.substring(5)
      })

      let dataShadow = []

      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        calculable: true,
        color: ['#6156e4', '#4fa8f9', '#bd5ee9'],
        xAxis: [
          {
            type: 'category',
            triggerEvent: true,
            data: xAxis
          }
        ],
        yAxis: {
          axisLine: {
            show: true
          },
          axisTick: {
            show: true,
            textStyle: {
              color: '#999'
            }
          }
        },
        series: [
          {
            type: 'bar',
            itemStyle: {
              color: 'rgba(0,0,0,0.05)'
            },
            barGap: '-100%',
            barCategoryGap: '40%',
            data: dataShadow
          },
          {
            type: 'bar',
            barWidth: dataShadow.length >= 30 ? null : 30,
            /* itemStyle: {
              color: new echarts.graphic.LinearGradinent(0,0,0,1,[{}])
            } */
            data: odata,
            label: {
              normal: {
                show: true,
                position: 'top'
              }
            }
          }
        ]
      }
      this.dataChart.setOption(option)
      this.dataChart.resize()
    },
    getDay(day) {
      let today = new Date()
      let targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
      today.setTime(targetday_milliseconds)
      let tYear = today.getFullYear()
      let tMonth = today.getMonth()
      let tDate = today.getDate()

      tMonth = this.doHandleZero(tMonth + 1)
      tDate = this.doHandleZero(tDate)
      return tYear + '-' + tMonth + '-' + tDate
    },
    doHandleZero(value) {
      let m = value
      if (value.toString().length === 1) {
        m = '0' + value
      }
      return m
    },
    clearDrawer() {
      this.tagId = ''
      this.tagNm = ''
      this.orgId = ''
      this.chartList = []
      this.dataChart = null
      this.$refs.orgList.reset()
      this.$refs.codeList.reset()
      this.drawerVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.monitor-detail-page {
  .indicator-name {
    font-size: 17px;
    font-weight: 700;
    text-align: center;
  }
  .tag-data-wrap {
    height: 300px;
    margin-top: 22px;
  }
  #echart {
    height: 300px;
  }
  .title-tips {
    font-size: 14px;
    padding-left: 5px;
    color: #787878;
    vertical-align: unset;
    position: static;
  }
  .no-record {
    text-align: center;
    line-height: 32px;
    color: #787878;
  }
}
</style>
